#include <poll.h>
#include "Socket.hpp"
#include "log.hpp"

static const uint16_t defaultport = 8000;
static const int fd_max = 64;
int defaultfd = -1;
int non_event = 0;

class PollServer
{
public:
    PollServer()
    {
        for (int i = 0; i < fd_max; i++)
        {
            _event_fds[i].fd = defaultfd;
            _event_fds[i].events = non_event;
            _event_fds[i].revents = non_event;
        }
    }

    bool Init()
    {
        _listensocket.Socket();
        int opt = 1;
        setsockopt(_listensocket._sockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
        _listensocket.Bind(defaultport);
        _listensocket.Listen();

        return true;
    }

    void Accepter()
    {
        cout << "get a new link" << endl;
        std::string clientip;
        uint16_t clinetport = 0;
        int sock = _listensocket.Accept(&clientip, &clinetport);
        if (sock < 0)
        {
            return;
        }
        lg.logmessage(info, "accept success,%s:%d.%d", clientip.c_str(), clinetport, sock);
        // 添加sock
        int pos = 1;
        for (; pos < fd_max; pos++)
        {
            if (_event_fds[pos].fd != defaultfd)
            {
                continue;
            }
            else
            {
                break;
            }
        }

        if (pos == fd_max)
        {
            lg.logmessage(warning, "server is full,close %d", sock);
            close(sock);
            // 可以扩容
        }
        else
        {
            _event_fds[pos].fd = sock;
            _event_fds[pos].events = POLLIN;
            _event_fds[pos].revents = non_event;
            // 打印查看fdary
            PrintFd();
        }
    }

    void Recver(int fd, int pos)
    {
        char buff[1024];
        ssize_t n = read(fd, buff, sizeof(buff) - 1);
        if (n > 0)
        {
            buff[n] = 0;
            cout << "get message:" << buff << endl;
        }
        else if (n == 0)
        {
            lg.logmessage(info, "client quit, me too, fd:", fd);
            close(fd);
            _event_fds[pos].fd = defaultfd; // 这里本质是移除
        }
        else
        {
            lg.logmessage(warning, "recv error,fd:", fd);
            close(fd);
            _event_fds[pos].fd = defaultfd; // 这里本质是移除
        }
    }

    void Dispatcher()
    {
        // 遍历找出就绪描述符
        for (int i = 0; i < fd_max; i++)
        {
            int fd = _event_fds[i].fd;
            if (fd == defaultfd)
                continue;

            if (_event_fds[i].revents & POLLIN)
            {
                // 监听就绪
                if (fd == _listensocket.Fd())
                {
                    Accepter();
                }
                else // 读就绪
                {
                    Recver(fd, i);
                }
            }
        }
    }

    void Start()
    {
        // listen套接字放入第一个，并设置读事件
        _event_fds[0].fd = _listensocket.Fd();
        _event_fds[0].events = POLLIN;
        int timeout = 3000;  // 3s
        for (;;)
        {
            // poll函数
            int n = poll(_event_fds, fd_max, timeout);
            // 就绪不处理,会一直通知,这时读取不会阻塞
            switch (n)
            {
            case 0:
                cout << "timeout..." << endl;
                break;
            case -1:
                cerr << "poll error" << endl;
                break;
            default:
                // 有事件就绪,todo
                Dispatcher();
                break;
            }
        }
    }

    void PrintFd()
    {
        cout << "online fd list: ";
        for (int i = 0; i < fd_max; i++)
        {
            if (_event_fds[i].fd == defaultfd)
                continue;
            cout << _event_fds[i].fd << " ";
        }
        cout << endl;
    }

    ~PollServer()
    {
        _listensocket.Close();
    }

private:
    Sock _listensocket;
    struct pollfd _event_fds[fd_max];  // 用户维护的数组
};

